package cn.buyclss.microapp.service.impl;

import cn.buyclss.microapp.entity.domain.Customer;
import cn.buyclss.microapp.entity.domain.GoodsSpecs;
import cn.buyclss.microapp.entity.domain.GoodsSpecsExample;
import cn.buyclss.microapp.entity.domain.Order;
import cn.buyclss.microapp.entity.domain.OrderExample;
import cn.buyclss.microapp.entity.domain.OrderGoodsSpecs;
import cn.buyclss.microapp.entity.dto.GoodsSpecsInsertDTO;
import cn.buyclss.microapp.entity.dto.UpdateGoodsSpecsDTO;
import cn.buyclss.microapp.entity.po.OrdersWithShopAndSpecsAndStatusPO;
import cn.buyclss.microapp.entity.support.RespResult;
import cn.buyclss.microapp.entity.vo.GoodsSpecsVO;
import cn.buyclss.microapp.entity.vo.OrderVO;
import cn.buyclss.microapp.mapper.GoodsSpecsMapper;
import cn.buyclss.microapp.mapper.OrderGoodsSpecsMapper;
import cn.buyclss.microapp.mapper.OrderMapper;
import cn.buyclss.microapp.service.OrderService;
import cn.buyclss.microapp.service.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: Cecurio
 * @create: 2019-03-22 12:11
 **/
@Service
public class OrderServiceImpl implements OrderService {

    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    GoodsSpecsMapper goodsSpecsMapper;

    @Autowired
    private OrderGoodsSpecsMapper orderGoodsSpecsMapper;

    @Override
    @Transactional
    public RespResult addOneOrder(OrderVO orderVO) {
        RespResult res = RespResult.successInstance();

        logger.info(orderVO.toString());
        // ns_order表插入一条，拿到orderID
        Customer customer = userInfoService.getUserInfo();
        Integer uid = customer.getId();
        Order newOrder = new Order();
        newOrder.setUid(uid);
        newOrder.setShopId(orderVO.getShopId());
        newOrder.setOrderStatus(1);
        newOrder.setCreatedTime(new Date());
        newOrder.setUpdatedTime(new Date());
        newOrder.setMarked(0);
        newOrder.setGoodMark(0);
        newOrder.setEvaluationWord("还未评价！");

        orderMapper.insertSelective(newOrder);

        int newOrderId = newOrder.getId();

        for (int i = 0; i < orderVO.getSpecsList().size(); i++) {
            GoodsSpecsVO tempGoodsSpecsVO = orderVO.getSpecsList().get(i);
            // 检查库存
            GoodsSpecsExample goodsSpecsExample = new GoodsSpecsExample();
            GoodsSpecsExample.Criteria goodsSpecsExampleCriteria = goodsSpecsExample.createCriteria();
            goodsSpecsExampleCriteria.andIdEqualTo(tempGoodsSpecsVO.getGoodsSpecsId());
            List<GoodsSpecs> goodsSpecsList = goodsSpecsMapper.selectByExample(goodsSpecsExample);
            if (goodsSpecsList == null || goodsSpecsList.size() < 1) {
                return RespResult.failureInstance("不存在编号为" + tempGoodsSpecsVO.getGoodsSpecsId() + "的商品");
            }
            GoodsSpecs tempGoodsSpecs = goodsSpecsList.get(0);
            if (tempGoodsSpecs.getStockNum() < tempGoodsSpecsVO.getPurchaseCount()) {
                return RespResult.failureInstance("编号为" + tempGoodsSpecsVO.getGoodsSpecsId() + "的商品 库存不足");
            }
        }

        // 减库存
        for (int i = 0; i < orderVO.getSpecsList().size(); i++) {
            GoodsSpecsVO tempGoodsSpecsVO = orderVO.getSpecsList().get(i);
            UpdateGoodsSpecsDTO updateGoodsSpecsDTO = new UpdateGoodsSpecsDTO();
            updateGoodsSpecsDTO.setGoodsSpecsId(tempGoodsSpecsVO.getGoodsSpecsId());
            updateGoodsSpecsDTO.setPurchaseCount(tempGoodsSpecsVO.getPurchaseCount());
            goodsSpecsMapper.reduceStockById(updateGoodsSpecsDTO);
        }

        // ns_order_goods_specs表插入多条
        List<GoodsSpecsInsertDTO> goodsSpecsInsertDTOS = new ArrayList<>();
        for (int i = 0; i < orderVO.getSpecsList().size(); i++) {
            GoodsSpecsVO tempGoodsSpecsVO = orderVO.getSpecsList().get(i);
            GoodsSpecsInsertDTO tempInsertDTO = new GoodsSpecsInsertDTO();
            tempInsertDTO.setOrderId(newOrderId);
            tempInsertDTO.setSpecsId(tempGoodsSpecsVO.getGoodsSpecsId());
            tempInsertDTO.setPurchaseCount(tempGoodsSpecsVO.getPurchaseCount());
            goodsSpecsInsertDTOS.add(tempInsertDTO);
        }

        goodsSpecsMapper.addBatch(goodsSpecsInsertDTOS);
        res.putValue("newOrderId", newOrderId);
        return res;
    }

    @Override
    public RespResult confirmPay(Integer orderId) {
        RespResult res = RespResult.successInstance();
        OrderExample example = new OrderExample();
        OrderExample.Criteria cr = example.createCriteria();
        cr.andIdEqualTo(orderId);
        List<Order> orderList = orderMapper.selectByExample(example);
        if (orderList == null || orderList.size() < 1) {
            return RespResult.failureInstance("该订单不存在呢！");
        }

        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus(2);
        orderMapper.updateByPrimaryKeySelective(order);
        return res;
    }

    @Override
    public RespResult confirmGoodsAccepted(Integer orderId) {
        RespResult res = RespResult.successInstance();
        OrderExample example = new OrderExample();
        OrderExample.Criteria cr = example.createCriteria();
        cr.andIdEqualTo(orderId);
        List<Order> orderList = orderMapper.selectByExample(example);
        if (orderList == null || orderList.size() < 1) {
            return RespResult.failureInstance("该订单不存在呢！");
        }

        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus(4);
        orderMapper.updateByPrimaryKeySelective(order);
        return res;
    }

    /**
     * 获取微信用户的订单
     *
     * @return
     */
    @Override
    public RespResult getMyOrders(Integer pageIndex, Integer pageSize) {
        RespResult res = RespResult.successInstance();
        Customer customer = userInfoService.getUserInfo();
        Integer uid = customer.getId();
        PageHelper.startPage(pageIndex, pageSize);
        List<OrdersWithShopAndSpecsAndStatusPO> list = orderMapper.selectOrdersWithShopAndSpecsAndStatusByCustomId(uid);

        PageInfo<OrdersWithShopAndSpecsAndStatusPO> pageInfo = new PageInfo<OrdersWithShopAndSpecsAndStatusPO>(list);
        res.putValue("orders", pageInfo);
        return res;
    }
}
